﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using SubStationManagement.Server.Models;

namespace SubStationManagement.Server.Services
{
    public class MeasureModuleService
    {
        private readonly IMongoCollection<MeasureModule> _measureModulesCollection;

        public MeasureModuleService(
            IOptions<SubStationDatabaseSettings> subStationDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                subStationDatabaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                subStationDatabaseSettings.Value.DatabaseName);

            _measureModulesCollection = mongoDatabase.GetCollection<MeasureModule>(
                subStationDatabaseSettings.Value.MeasureModulesCollectionName);
        }

        public async Task<List<MeasureModule>> GetAsync() =>
            await _measureModulesCollection.Find(_ => true).ToListAsync();

        public List<MeasureModule> GetAll() =>
            _measureModulesCollection.Find(_ => true).ToList();

        public async Task<MeasureModule?> GetAsync(string id) =>
            await _measureModulesCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(MeasureModule newMeasureModule) =>
            await _measureModulesCollection.InsertOneAsync(newMeasureModule);

        public async Task UpdateAsync(string id, MeasureModule updatedMeasureModule) =>
            await _measureModulesCollection.ReplaceOneAsync(x => x.Id == id, updatedMeasureModule);

        public async Task RemoveAsync(string id) =>
            await _measureModulesCollection.DeleteOneAsync(x => x.Id == id);
    }
}
